#include "sk_recipe_manage.h"
#include "ui_sk_recipe_manage.h"
#include <QDebug>
#include <QSettings>
#include <QTextCodec>
#include "pub_var.h"
#include <QMessageBox>
#include <QSqlError>

RecipeManage::RecipeManage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecipeManage)
{
    ui->setupUi(this);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setIniCodec(QTextCodec::codecForName("UTF_8"));

    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/recipe_manage").toRect();
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);

    md_oper = new QSqlQueryModel();
    md_invoice = new QSqlQueryModel();
    md_unused = new QSqlQueryModel();

    //当前最大发票号码
    qro->exec("SELECT max(end_no) FROM fin_com_invoice");
    qro->next();

    cur_max_sn = qro->value(0).toInt();

    tm_init = new QTimer(this);
    connect(tm_init, &QTimer::timeout, this, &RecipeManage::on_tm_init_timeout);
    tm_init->start(100);

}

RecipeManage::~RecipeManage()
{
    delete ui;
}

void RecipeManage::on_tm_init_timeout()
{
    tm_init->stop();

    //显示收费员列表
    sq = "select  LPAD(code, 6, '0') 代码, name 姓名 "
         " from com_privileges where role_dept = '收款员'";
    md_oper->setQuery(sq, pub::db_m);
    ui->tv_oper->setModel(md_oper);
    pub::setColumnWidth(ui->tv_oper, "0.4^0.4", ui->tv_oper->width());

    //当前可用起始发票号
    ui->le_invoice_sn_start->setText( pub::add0( QString::number(cur_max_sn + 1), 12));
}


void RecipeManage::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setIniCodec(QTextCodec::codecForName("UTF_8"));
    setIni.setValue("windowState/recipe_manage", QVariant(this->geometry()));
    emit destroyW( "recipe_manage" );

}

void RecipeManage::on_pb_exit_clicked()
{
    close();
}

void RecipeManage::on_pb_save_clicked()
{
    QString name = ui->le_oper_name->text();

    if(name.isEmpty())
    {
        QMessageBox::information(this, "注意", "未选择操作对象！");
        return;
    }

    QString code = ui->le_oper_code->text();
    int count = ui->le_invoice_count->text().toUInt();
    if(count < 1)
    {
        QMessageBox::information(this, "注意", "票据张数数据无效！");
        return;
    }



    QString iv_name = ui->cb_invoice_type->currentText();
    QString iv_code;
    if(iv_name == "门诊收费")
    {
        iv_code = "C";
    }
    else if(iv_name == "挂号")
    {
        iv_code = "R";
    }
    else
    {
        QMessageBox::information(this, "注意", "发票类型无效！");
        return;
    }

    sq = "INSERT INTO fin_com_invoice ("//  --发票领取记录\n"//
         "get_dtime,"//   --时间\n"
         "get_person_code,"//   --领取人\n"
         "invoice_kind,"//   --发票种类 C , R \n"
         "invoice_name,"//   --C门诊发票 R住院发票 \n"
         "start_no,"//   --发票开始号\n"
         "end_no,"//   --发票终止号\n"
         "used_no,"//   --发票已用号\n"
         "used_state,"//   --1：使用，0：未用，-1：已用\n"
         "is_pub,"//   --公用标志\n"
         "oper_code,"//   --操作员\n"
         "oper_date"//   --操作时间\n"
         ") VALUES ("
         "sysdate,"
         "'%1',"//   --领取人\n"
         "'%2',"//   --发票种类 C , R \n"
         "'%3',"//   --C门诊发票 R住院发票 \n"
         "'%4',"//   --发票开始号\n"
         "'%5',"//   --发票终止号\n"
         "'%6',"//   --发票已用号\n"
         "'0',"//   --1：使用，0：未用，-1：已用\n"
         "'0',"//   --公用标志\n"
         "'%7',"//   --操作员\n"
         "sysdate )"; //  --操作时间\n";
    sq = sq.arg(ui->le_oper_code->text());  //   --领取人\n"
    sq = sq.arg(iv_code);//   --发票种类 C , R \n"
    sq = sq.arg(iv_name);//   --C门诊发票 R住院发票 \n"
    sq = sq.arg( pub::add0( QString::number(cur_max_sn + 1), 12));//   --发票终止号\n"
    sq = sq.arg( pub::add0( QString::number(cur_max_sn + count), 12));//   --发票已用号\n"
    sq = sq.arg( pub::add0( QString::number(cur_max_sn ), 12));//   --发票已用号\n"
    sq = sq.arg(pub::usr_code);//   --操作员\n"
    qDebug()<<"插入发票记录：" << sq;

    if(!qro->exec(sq))
    {

        QMessageBox::information(this, "注意", "插入数据失败！\n" + qro->lastError().text());
        return;
    }

    cur_max_sn = cur_max_sn + count;

    ui->le_invoice_count->clear();
    ui->le_invoice_sn_start->setText( pub::add0( QString::number(cur_max_sn + 1), 12));

}

void RecipeManage::on_tv_oper_clicked(const QModelIndex &index)
{
    ui->le_oper_code->setText(index.siblingAtColumn(0).data().toString());
    ui->le_oper_name->setText(index.siblingAtColumn(1).data().toString());
}

void RecipeManage::on_tv_oper_doubleClicked(const QModelIndex &index)
{
    on_tv_oper_clicked(index);
}

void RecipeManage::on_pb_fresh_clicked()
{
    QString tmp_sq = "";

    QString name = ui->le_oper_name->text();
    if(!name.isEmpty())
    {
        tmp_sq += " and get_person_code = '" + ui->le_oper_code->text() + "' ";
    }

    QString iv_name = ui->cb_invoice_type->currentText();
    QString iv_code = "";
    if(iv_name == "门诊收费")
    {
        iv_code = "C";
    }
    else if(iv_name == "挂号")
    {
        iv_code = "R";
    }

    tmp_sq += " and invoice_kind like '%" + iv_code + "%' ";

    QString tmp_status = "9";

    if(ui->ckb_used->isChecked())
    {
        tmp_status += ",-1";
    }

    if(ui->ckb_unuse->isChecked())
    {
        tmp_status += ",0";
    }

    if(ui->ckb_inuse->isChecked())
    {
        tmp_status += ",1";
    }


    if(tmp_status == "9")
    {
        QMessageBox::information(this, "注意", "未选定发票状态！" );
        return;
    }

    tmp_sq += " and used_state in (" + tmp_status + ")";

    sq = "select get_dtime 领取时间,"
         " get_person_code 领取人,"
         " invoice_name 发票类型,"
         " start_no 起始号,"
         " end_no 终止号,"
         " case when used_state = 0 then '未用' else "
         " (case when used_state = 1 then '在用' else '已用' end) end 使用状态"
         " from fin_com_invoice "
         " where 1 = 1 " + tmp_sq;

    qDebug()<<"提取发票明细"<<sq;
    md_invoice->setQuery(sq, pub::db_o);
    ui->tv_invoice->setModel(md_invoice);
    pub::setColumnWidth(ui->tv_invoice, "0.25^0.1^0.1^0.18^0.18^0.1", ui->tv_invoice->width());

}

void RecipeManage::on_pb_invoice_return_clicked()
{
    if(ui->le_oper->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "未指定号段！");
        return;
    }

    QMessageBox::Button bt;
    bt = QMessageBox::question(this, "注意", "是否退回指定号段的发票？");

    if(bt != QMessageBox::Yes)
    {
        return;
    }

    sq = "delete from fin_com_invoice where "
         " start_no = '%1' "
         " and end_no = '%2'"
         " and invoice_name = '%3'";

    sq = sq.arg(ui->le_sn_start->text())
            .arg(ui->le_sn_end->text())
            .arg(ui->le_type->text());

    qDebug()<<"退回已经发放的票据号段："<<sq;

    qro->exec(sq);

    ui->le_oper->clear();
    ui->le_sn_end->clear();
    ui->le_sn_start->clear();
    ui->le_type->clear();

    on_pb_search_clicked();

}

void RecipeManage::on_pb_search_clicked()
{

    sq = "SELECT get_dtime 领取时间, e.empl_name 收费员, INVOICE_NAME 类型, "
         " START_NO 起始号, END_NO 终止号 "
         " FROM fin_com_invoice f "
         " left join com_employee e on e.empl_code = f.get_person_code "
         " where USED_STATE = 0 order by GET_DTIME";

    qDebug()<<"提取未使用发票列表："<<sq;
    md_unused->setQuery(sq, pub::db_o);
    ui->tv_unused_invoice->setModel(md_unused);
    pub::setColumnWidth(ui->tv_unused_invoice, "0.2^0.18^0.18^0.18^0.18", ui->tv_unused_invoice->width());

}

void RecipeManage::on_tv_unused_invoice_clicked(const QModelIndex &index)
{
    ui->le_oper->setText(index.siblingAtColumn(1).data().toString());
    ui->le_type->setText(index.siblingAtColumn(2).data().toString());
    ui->le_sn_start->setText(index.siblingAtColumn(3).data().toString());
    ui->le_sn_end->setText(index.siblingAtColumn(4).data().toString());
}

void RecipeManage::on_tv_unused_invoice_doubleClicked(const QModelIndex &index)
{
    on_tv_unused_invoice_clicked(index);
}
